﻿using BeetleX;
using BeetleX.EventArgs;
using Microsoft.Extensions.Logging;
using System;
namespace Athena.Transport.BeetleX
{
    using Codec;
    using Message;
    public class BeetleXRpcServiceHandler : ServerHandlerBase
    {
        private readonly IRpcMessageEncoder _rpcMessageEncoder;
        private readonly IRpcMessageDecoder _rpcMessageDecoder;
        private readonly ILogger _logger;

        public Action<ITransportMessageSender, RpcTransportMessage> _transportMessageAction;

        public BeetleXRpcServiceHandler(IRpcMessageEncoder rpcMessageEncoder, IRpcMessageDecoder rpcMessageDecoder, ILogger<BeetleXRpcServiceHandler> logger, Action<ITransportMessageSender, RpcTransportMessage> transportMessageAction)
        {
            _rpcMessageEncoder = rpcMessageEncoder;
            _rpcMessageDecoder = rpcMessageDecoder;
            _logger = logger;
            _transportMessageAction = transportMessageAction;
        }

        public override void SessionReceive(IServer server, SessionReceiveEventArgs e)
        {
            var pipeStream = e.Stream.ToPipeStream();
            var rpcTransportMessage = _rpcMessageDecoder.MessageDecoding(pipeStream.ReadUTF());

            var serviceSender = new BeetleXTransportMessageServerSender(pipeStream, _rpcMessageEncoder, _logger);

            _transportMessageAction.Invoke(serviceSender, rpcTransportMessage);
        }
    }
}
